package com.kedacom.freedomLabel.view.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import com.google.gson.Gson;
import com.hard.CardReadHelp;
import com.hard.ReturnValue;
import com.hard.ReturnValueCallback;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivitySelectItemBinding;
import com.kedacom.freedomLabel.initdata.bean.CategoryNewBean;
import com.kedacom.freedomLabel.initdata.bean.Classes;
import com.kedacom.freedomLabel.initdata.bean.Goods;
import com.kedacom.freedomLabel.initdata.bean.Staff;
import com.kedacom.freedomLabel.initdata.bean.Team;
import com.kedacom.freedomLabel.initdata.dao.CategoryNewDao;
import com.kedacom.freedomLabel.initdata.dao.ClassesDao;
import com.kedacom.freedomLabel.initdata.dao.GoodsDao;
import com.kedacom.freedomLabel.initdata.dao.StaffDao;
import com.kedacom.freedomLabel.initdata.dao.TeamDao;
import com.kedacom.freedomLabel.model.SelectType;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.bean.Operator;
import com.kedacom.freedomLabel.model.bean.Product;
import com.kedacom.freedomLabel.model.bean.Template;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.dao.CategoryDao;
import com.kedacom.freedomLabel.model.db.dao.ItemDao;
import com.kedacom.freedomLabel.model.db.dao.OperatorDao;
import com.kedacom.freedomLabel.model.db.dao.ProductDao;
import com.kedacom.freedomLabel.model.db.dao.TemplateDao;
import com.kedacom.freedomLabel.view.fragment.ListDataFragment;
import com.kedacom.freedomLabel.viewmodel.SelectItemViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.message.LegoMessageManager;

import java.util.List;


@ContentView(R.layout.activity_select_item)
@ViewModel(SelectItemViewModel.class)
public class SelectItemActivity extends BaseActivity<ActivitySelectItemBinding, SelectItemViewModel> {

    private String mSearchKey;
    private CardReadHelp mReadCardHelp;
    @SuppressLint("HandlerLeak")
    private Handler mScaleHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if(msg.obj.toString().contains("&")){
                    String[] CardNum= msg.obj.toString().split("&");

                    OperatorDao dao = AppDatabase.getInstance().operatorDao();
                    List<Operator> operatorList = dao.get(CardNum[0]);
                    AlertDialog.Builder builder = new AlertDialog.Builder(SelectItemActivity.this);
                    if(operatorList.size()>0){
                        builder.setTitle("持有该卡人员已存在，名字为："+operatorList.get(0).name);
                    }else {
                        builder.setTitle("读取数据");
                    }
                    builder.setMessage("名字："+CardNum[1]+"\n卡号："+CardNum[0]);

                    builder.setNegativeButton("取消", (dialog, which) -> {
//                        Intent intent =new int
                    });
                    builder.setPositiveButton("确定", (dialog, which) -> {
                        Operator operator=new Operator();
                        operator.name=CardNum[1];
                        operator.cardNumber=CardNum[0];

                        if(operatorList.size()<=0){
                            dao.save(operator);
                        }else {
                            operator=operatorList.get(0);
                        }
                        Intent intent = getIntent();
                        Gson gson = new Gson();
                        String toJson = gson.toJson(operator);
                        intent.putExtra(Options.KEY_SELECT_RESULT, toJson);
                        setResult(RESULT_OK, intent);
                        finish();

                    });
                    builder.show();



                }else {
                    showToast(msg.obj.toString(), TOAST_WARNING);
                }
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSearchView();
        mReadCardHelp = CardReadHelp.getSingleton(); //new CardReadHelp();
        SelectType type = (SelectType) getIntent().getSerializableExtra(Options.KEY_SELECT_TYPE);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (type == SelectType.TYPE_ITEM) {
            ItemDao itemDao = AppDatabase.getInstance().itemDao();
            String itemCategory = getIntent().getStringExtra(Options.KEY_ITEM_CATEGORY);
            ListDataFragment<Item> fragment = ListDataFragment.newInstance(itemDao, itemCategory, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        } else if (type == SelectType.TYPE_PRODUCT) {
            ProductDao productDao = AppDatabase.getInstance().productDao();
            ListDataFragment<Product> fragment = ListDataFragment.newInstance(productDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        } else if (type == SelectType.TYPE_CATEGORY) {
            CategoryNewDao categoryNewDao = AppDatabase.getInstance().getCategoryNewDao();
            ListDataFragment<CategoryNewBean> fragment = ListDataFragment.newInstance(categoryNewDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
//            CategoryDao categoryDao = AppDatabase.getInstance().categoryDao();
//            ListDataFragment<Category> fragment = ListDataFragment.newInstance(categoryDao, false);
//            transaction.add(mBinding.listDataLayout.getId(), fragment);
        } else if (type == SelectType.TYPE_LABEL) {
            TemplateDao templateDao = AppDatabase.getInstance().templateDao();
            ListDataFragment<Template> fragment = ListDataFragment.newInstance(templateDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        } else if (type == SelectType.TYPE_OPERATOR) {
            OperatorDao operatorDao = AppDatabase.getInstance().operatorDao();
            ListDataFragment<Operator> fragment = ListDataFragment.newInstance(operatorDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);

            // 显示用户读卡按钮
            mBinding.buttonSwipeCard.setVisibility(View.VISIBLE);
            mBinding.buttonSwipeCard.setOnClickListener(v -> {
                // TODO: 2020/6/5 执行读卡逻辑
//                if (mReadCardHelp != null){
//                    mReadCardHelp.cancelReadCard(null);
//                }
                mReadCardHelp.readCardId(new ReturnValueCallback() {
                    @Override
                    public void run(ReturnValue result) {
                        if (result != null) {
                            Message message = Message.obtain();
                            message.what = 0;
                            String msg;
                            Object tag = result.getTag();
                            if (tag != null)
                                msg = tag.toString();
                            else
                                msg = "未知错误";
                            message.obj = msg;
                            mScaleHandler.sendMessage(message);
                        }
                    }
                });



            });
        }else if (type == SelectType.TYPE_ClASSES) {
            ClassesDao classesDao = AppDatabase.getInstance().getClassesDao();
            ListDataFragment<Classes> fragment = ListDataFragment.newInstance(classesDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        }else if (type == SelectType.TYPE_GOODS) {
            GoodsDao goodsDao = AppDatabase.getInstance().getGoodsDao();
            ListDataFragment<Goods> fragment = ListDataFragment.newInstance(goodsDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        }else if (type == SelectType.TYPE_TEAM) {
            TeamDao teamDao = AppDatabase.getInstance().getTeamDao();
            ListDataFragment<Team> fragment = ListDataFragment.newInstance(teamDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        }else if (type == SelectType.TYPE_STAFF) {
            StaffDao staffDao = AppDatabase.getInstance().getStaffDao();
            ListDataFragment<Staff> fragment = ListDataFragment.newInstance(staffDao, false);
            transaction.add(mBinding.listDataLayout.getId(), fragment);
        }
        transaction.commit();
    }


    @Override
    protected void onStop() {
        super.onStop();
//            if (mReadCardHelp != null){
//                mReadCardHelp.cancelReadCard(null);}
    }

    @OnMessage(value = Options.MSG_SELECT_ITEM)
    public <T> void receiveItemClickMessage(T data) {
        Intent intent = getIntent();
        Gson gson = new Gson();
        String toJson = gson.toJson(data);
        intent.putExtra(Options.KEY_SELECT_RESULT, toJson);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void onAddItemButtonClick(View view) {
        beep();
        SelectType type = (SelectType) getIntent().getSerializableExtra(Options.KEY_SELECT_TYPE);
        if (type == null) return;
        if (type == SelectType.TYPE_ITEM) {
        } else if (type == SelectType.TYPE_PRODUCT) {
        } else if (type == SelectType.TYPE_CATEGORY) {
        } else if (type == SelectType.TYPE_LABEL) {
        } else if (type == SelectType.TYPE_OPERATOR) {
        }
    }

    public void onBackButtonClick(View view) {
        beep();
        onBackPressed();
    }

    /**
     * 初始化搜索控件
     */
    protected void initSearchView() {
        mBinding.searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (mBinding.searchClear.getVisibility() == View.INVISIBLE) {
                        mBinding.searchClear.setVisibility(View.VISIBLE);
                        mBinding.searchClear.setClickable(true);
                    }
                } else {
                    if (mBinding.searchClear.getVisibility() == View.VISIBLE) {
                        mBinding.searchClear.setVisibility(View.INVISIBLE);
                        mBinding.searchClear.setClickable(false);
                    }
                }
                mSearchKey = s.toString().trim();
            }
        });

        mBinding.searchText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                closeSoftKeyboard();
                String[] data = new String[2];
                String itemCategory = getIntent().getStringExtra(Options.KEY_ITEM_CATEGORY);
                data[0] = null;
                data[1] = mSearchKey;
                LegoMessageManager.getInstance().sendMessage(Options.MSG_UPDATE_LIST_PARAM, data);
                return true;
            }
            return false;
        });

        mBinding.searchClear.setOnClickListener(v -> {
            mBinding.searchText.setText(null);
            mSearchKey = null;
            closeSoftKeyboard();
            String itemCategory = getIntent().getStringExtra(Options.KEY_ITEM_CATEGORY);
            String[] data = new String[2];
            data[0] = itemCategory;
            data[1] = null;
            LegoMessageManager.getInstance().sendMessage(Options.MSG_UPDATE_LIST_PARAM, data);
        });
    }

    private void closeSoftKeyboard() {
        View currentFocusView = getCurrentFocus();
        if (currentFocusView != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(currentFocusView.getWindowToken(), 0);
        }
    }
}